<?php

session_start();
include_once dirname(dirname(__FILE__)) . '/include/core/image.php';
include_once dirname(dirname(__FILE__)) . '/include/common.php';
$core = new core();
$product_id = isset($_POST["product_id"]) ? intval($_POST["product_id"]) : 0;
$product_name = isset($_POST["product_name"]) ? addslashes(trim($_POST["product_name"])) : '';
$product_code = isset($_POST["product_code"]) ? addslashes(trim($_POST["product_code"])) : '';
$link_web = isset($_POST["link_web"]) ? addslashes(trim($_POST["link_web"])) : '';
$product_price = isset($_POST["product_price"]) ? $_POST["product_price"] : 0;
$store_price = isset($_POST["store_price"]) ? $_POST["store_price"] : 0;
$stamp_price = isset($_POST["stamp_price"]) ? $_POST["stamp_price"] : 0;
$product_size = isset($_POST["product_size"]) ? addslashes(trim($_POST["product_size"])) : '';

$product_category = isset($_POST["product_category"]) ? intval($_POST["product_category"]) : 0;
$folder_temp = isset($_POST["folder_temp"]) ? addslashes(trim($_POST["folder_temp"])) : '';
$description = isset($_POST["description"]) ? addslashes(trim($_POST["description"])) : '';
$array_photo_list = isset($_POST["array_photo_list"]) ? $_POST["array_photo_list"] : array();
$array_photo_color = isset($_POST["array_photo_color"]) ? $_POST["array_photo_color"] : array();
$array_is_main_photo = isset($_POST["array_is_main_photo"]) ? $_POST["array_is_main_photo"] : array();
$from_order_detail = isset($_POST["from_order_detail"]) ? $_POST["from_order_detail"] : 0;
//edit price
$product_price = floatval(preg_replace('/[^\d.]/', '', $product_price));
$product_price = $product_price * 1000;
$store_price = floatval(preg_replace('/[^\d.]/', '', $store_price));
$stamp_price = floatval(preg_replace('/[^\d.]/', '', $stamp_price));
$product = '';
if ($product_id > 0) {
    $product = $core->getProductById($product_id);
    if (!$product) {
        echo json_encode(array('type' => 1, 'msg' => "Sản phẩm không tồn tại!"));
        die;
    }
} else {
    $check_exist = $core->getProductInfoByCode($product_code);
    if ($check_exist) {
        echo json_encode(array('type' => 1, 'msg' => "Sản phẩm đã tồn tại, vui lòng tìm và sửa sản phẩm này!"));
        die;
    }
}
//if ($product_name == "") {
//    echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền tên sản phẩm!"));
//    die;
//}
if ($product_code == "") {
    echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền mã sản phẩm!"));
    die;
}
//if ($manufacture == "") {
//    echo json_encode(array('type' => 1, 'msg' => "Vui lòng điền thương hiệu!"));
//    die;
//}
if ($product_category == "") {
    echo json_encode(array('type' => 1, 'msg' => "Vui lòng nhập loại sản phẩm!"));
    die;
}
if (count($array_photo_color) <= 0) {
    echo json_encode(array('type' => 1, 'msg' => "Vui lòng nhập màu sản phẩm!"));
    die;
}
if ($folder_temp == "" || count($array_photo_list) <= 0) {
    echo json_encode(array('type' => 1, 'msg' => "Vui lòng chọn ảnh sản phẩm!"));
    die;
}

$category = $core->getCategoryId($product_category);
while($category->category_parent !=0){
    $category = $core->getCategoryId($category->category_parent);
}
$manufacture = $category->category_name;
$new_path_extra_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS;
$new_path_extra_photo_thumb = dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . "thumb_extra_photo" . DS;

$new_path_main_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS;
$new_path_main_thumb_photo = dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_";

$extra_photo_list_name = array();
$product_color = '';
$main_photo = '';
$old_product_price = 0;
if ($product_id > 0) {//update product
    $main_photo = $product->main_photo;
    //xóa ảnh sản phẩm nếu không thấy trong danh sách mới cập nhật
    $old_extra_photo = $product->extra_photo;
    if ($old_extra_photo != "") {
        $array_old_extra_photo = explode(",", $old_extra_photo);
        foreach ($array_old_extra_photo as $old_photo) {
            if (!in_array($old_photo, $array_photo_list)) {
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . $old_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . $old_photo);
                }
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . "thumb_extra_photo" . DS . $old_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . "extra_photo" . DS . "thumb_extra_photo" . DS . $old_photo);
                }
            } else {
                $extra_photo_list_name[] = $old_photo;
            }
        }
    }
    //update danh sach anh san pham
    $i = 0;
    foreach ($array_photo_list as $extra_photo_name) {
        //anh moi upload thi add vao danh sach, anh cu thi giu nguyen
        if (!in_array($extra_photo_name, $extra_photo_list_name)) {
            $new_photo_name = $array_photo_color[$i] . "_" . $product_code . "_" . $manufacture;
            $new_photo_name = $core->convert_string_friendly($new_photo_name) . ".jpg";
            $extra_photo_list_name[] = $new_photo_name;
            rename(dirname(dirname(__FILE__)) . DS . "tmp_photo" . DS . $folder_temp . DS . $extra_photo_name, $new_path_extra_photo . $new_photo_name);
            rename(dirname(dirname(__FILE__)) . DS . "tmp_photo" . DS . $folder_temp . DS . "200_" . $extra_photo_name, $new_path_extra_photo_thumb . $new_photo_name);
            //neu anh nay duoc chon lam anh dai dien-> luu thanh anh dai dien
            if ($array_is_main_photo[$i] == 1) {
                //xóa ảnh đại diện cũ đi trước khi tạo mới
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . $product->main_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . $product->main_photo);
                }
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $product->main_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $product->main_photo);
                }

                //tạo mới ảnh đại diện-> copy ảnh extra sang

                if (copy($new_path_extra_photo . $new_photo_name, $new_path_main_photo . $new_photo_name) && copy($new_path_extra_photo_thumb . $new_photo_name, $new_path_main_thumb_photo . $new_photo_name)) {
                    $main_photo = $new_photo_name;
                } else {
                    echo json_encode(array('type' => 2, 'msg' => "Tạo ảnh đại diện bị lỗi!"));
                }
            }
            $i++;
        } else {//anh nay da ton tai
            //thay đổi màu sản phẩm: kiem tra xem tên màu ảnh có bị thay đổi không? bị thay đổi thì phải thay lại tên ảnh với màu tương ứng
            $array_explode_photo_name = explode("_", $extra_photo_name);

            $is_change_name = false;
            if ($array_photo_color[$i] != $array_explode_photo_name[0]) {
                $new_photo_name = $array_photo_color[$i] . "_" . $array_explode_photo_name[1] . "_" . $array_explode_photo_name[2];
                rename($new_path_extra_photo . $extra_photo_name, $new_path_extra_photo . $new_photo_name);
                rename($new_path_extra_photo_thumb . $extra_photo_name, $new_path_extra_photo_thumb . $new_photo_name);
                $is_change_name = true;
                $key = array_search($extra_photo_name, $extra_photo_list_name);
                $extra_photo_list_name[$key] = $new_photo_name; //cap nhat ten moi vao mang photo
                //nếu thay tên của ảnh đang làm ảnh đại diện -> thay tên lại ảnh đại diện
                if ($extra_photo_name == $product->main_photo) {
                    rename($new_path_main_photo . $product->main_photo, $new_path_main_photo . $new_photo_name);
                    rename($new_path_main_thumb_photo . $product->main_photo, $new_path_main_thumb_photo . $new_photo_name);
                    $main_photo = $new_photo_name; //cap nhat ten anh dai dien trong DB
                }
            }
            // thay ảnh đại diện
            //chon anh khac lam anh dai dien thi xoa anh dai dien cu va update
            if ($extra_photo_name != $product->main_photo && $array_is_main_photo[$i] == 1) {
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . $product->main_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . $product->main_photo);
                }
                if (is_file(dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $product->main_photo)) {
                    unlink(dirname(dirname(__FILE__)) . DS . "photo" . DS . "thumb_photo" . DS . "200_" . $product->main_photo);
                }


                //nếu ảnh bị thay màu ở trên thì cập nhật lại tên file ảnh
                if ($is_change_name) {
                    $extra_photo_name = $new_photo_name;
                }
                if (copy($new_path_extra_photo . $extra_photo_name, $new_path_main_photo . $extra_photo_name) && copy($new_path_extra_photo_thumb . $extra_photo_name, $new_path_main_thumb_photo . $extra_photo_name)) {
                    $main_photo = $extra_photo_name;
                } else {
                    echo json_encode(array('type' => 2, 'msg' => "Tạo ảnh đại diện bị lỗi!"));
                }
            }
            $i++;
        }
    }
    $product_color = implode(",", $array_photo_color);
    $list_extra_photo = implode(",", $extra_photo_list_name);
    if ($product_price != $product->product_price) {
        $old_product_price = $product->product_price;
    }
    $core->db->query("UPDATE zen_product SET manufacture='$manufacture',product_name='$product_name',
            product_code='$product_code',product_category=$product_category,main_photo ='$main_photo',extra_photo='$list_extra_photo',
                description='$description',link_web='$link_web',product_price=$product_price,
                    old_product_price=$old_product_price,store_price=$store_price,
                     stamp_price=$stamp_price, product_size='$product_size',product_color='$product_color'  
             WHERE product_id=$product_id");
    echo json_encode(array('type' => 0, 'msg' => "Update thông tin sản phẩm thành công!", 'product_id' => $product_id));
    die;
} else {//them moi san pham
    $i = 0;
    foreach ($array_photo_list as $extra_photo_name) {
        $new_photo_name = $array_photo_color[$i] . "_" . $product_code . "_" . $manufacture;
        $new_photo_name = $core->convert_string_friendly($new_photo_name) . ".jpg";

        $extra_photo_list_name[] = $new_photo_name;
        rename(dirname(dirname(__FILE__)) . DS . "tmp_photo" . DS . $folder_temp . DS . $extra_photo_name, $new_path_extra_photo . $new_photo_name);
        rename(dirname(dirname(__FILE__)) . DS . "tmp_photo" . DS . $folder_temp . DS . "200_" . $extra_photo_name, $new_path_extra_photo_thumb . $new_photo_name);
        //neu anh moi upload nay duoc chon lam anh dai dien-> luu thanh anh dai dien
        if ($array_is_main_photo[$i] == 1) {
            if (copy($new_path_extra_photo . $new_photo_name, $new_path_main_photo . $new_photo_name) && copy($new_path_extra_photo_thumb . $new_photo_name, $new_path_main_thumb_photo . $new_photo_name)) {
                $main_photo = $new_photo_name;
            } else {
                echo json_encode(array('type' => 2, 'msg' => "Tạo ảnh đại diện bị lỗi!"));
            }
        }
        $i++;
    }
    $product_color = implode(",", $array_photo_color);
    $list_extra_photo = implode(",", $extra_photo_list_name);
    $core->db->query("INSERT INTO zen_product (`manufacture`,`product_name`,`product_code`,product_category,`main_photo`,
        `extra_photo`,`description`,`link_web`,`product_price`,`old_product_price`,
        `store_price`,`stamp_price`,`product_size`,`product_color`)
                        VALUES('$manufacture','$product_name','$product_code',$product_category,'$main_photo',
                            '$list_extra_photo','$description', '$link_web',$product_price,$old_product_price,
                        $store_price,$stamp_price,'$product_size','$product_color')");
    $product_id = $core->db->insert_id;
    if ($product_id > 0) {
        echo json_encode(array('type' => 0, 'msg' => "Thêm sản phẩm thành công!", 'product_id' => $product_id));
        die;
    } else {
        echo json_encode(array('type' => 1, 'msg' => "Thêm sản phẩm thất bại!"));
        die;
    }
}
?>